/* jzc 2020-02-03 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>

// 用于创建唯一的key
#define MSG_FILE "/etc/passwd" 

// 消息构造
struct msg_from {
    long mtype;
    char mtext[256];
};

int main(int argc, char **argv) {
    int msqid;
    key_t key;
    struct msg_from msg;

    // 获取key值
    if ((key = ftok(MSG_FILE, 'z')) < 0) {
        perror("ftok error!");
        exit(1);
    }

    // 打印key值
    printf("Message Queue - client key is: %d.\n", key);

    // 打开消息队列
    if ((msqid = msgget(key, IPC_CREAT|0777)) == -1) {
        perror("msgget error");
        exit(1);
    }

    // 打印进程队列ID及进程ID
    printf("My msqid is : %d\n", msqid);
    printf("My pid is : %d\n", getpid());

    // 添加消息，类型为888
    msg.mtype = 888;
    sprintf(msg.mtext, "Hello I am Client %d", getpid());
    msgsnd(msqid, &msg, sizeof(msg.mtext), 0);

    // 读取类型为999的消息队列
    msgrcv(msqid, &msg, 256, 999, 0);
    printf("Client: receive msg.mtext is: %s.\n", msg.mtext);
    printf("Client: receive msg.mtype is: %d.\n", msg.mtype);

    return 0;
}


